<template>
	<view >
		<u-navbar
		:autoBack="true" bgColor="var(--theme)"
		leftIconColor='#fff'
		:titleStyle="{ color: '#fff'}"
		 :title="isedit?'编辑订单':'新增订单'" rightText='' :border="false" :placeholder="true">
			<!-- <view slot="left"></view> -->
			<!-- <view slot="right" style="display: flex;">
				<u-icon name="clock" color="#fff" size="16" style="margin: 0 5px;"></u-icon>
				<u-icon name="plus-circle" color="#fff" size="16"></u-icon>
			</view> -->
		</u-navbar>
		 <view class="headBg  p20">
			 <view class="f-s-b">
			 	<view class="f-c">
			 		 <u-avatar src="https://chaoyuanhuishou.oss-cn-beijing.aliyuncs.com/head.png"  size="68"></u-avatar>
			 	</view>
			 	<view class="cf" @click="navTo('/pages/address/list?source=1')">
			 		<view class="">{{addressData.consignee || addressData.contactor}}{{addressData.phone}}</view>
					<view class="f-c mt20">
						<u-icon name="map" color="#fff" size="16"></u-icon>
						<span class="ml10" v-if="addressData.province">{{addressData.province}} {{addressData.city}} {{addressData.county}}</span>
						<span class="ml10" v-else>{{userInfo.address}}</span>
					</view>
			 	</view>
			 	<view class="">
			 		<u-icon name="arrow-right" color="#fff" size="24"></u-icon>
			 	</view>
			 </view>
		 	 
		 </view>
		 <view class="mainBox"  :style="{maxHeight:MainHeight}" >
		 	 <view class="f-s-b b-b c3 pt20 pb20" >
		 	 	<span>预约开始时间</span>
				<span class="f28">{{formatDate(date,'-')}}</span>
				<!-- <picker mode="date" @change="bindDateChange">
					<u-icon name="arrow-right" color="#333" size="20"></u-icon>
				</picker> -->
				<u-icon @click="show = true" name="arrow-right" color="#333" size="20"></u-icon>
				
		 	 </view>
			 <view class="f-s-b b-b c3 pt20 pb20" >
			 	<span>预约结束时间</span>
					<span class="f28">{{formatDate(date2,'-')}}</span>
					<!-- <picker mode="date" @change="bindDateChange">
						<u-icon name="arrow-right" color="#333" size="20"></u-icon>
					</picker> -->
					<u-icon @click="show2 = true" name="arrow-right" color="#333" size="20"></u-icon>
			 				
			 </view>
			 <view class="f-s-b b-b c3 pt20 pb20"  >
			 	<span>回收类目</span>
				<span class="f28">
					<span  v-for="item,ix in goodList" :key="ix">{{item.categorizeName}},</span>
				</span>
				<span></span>
			 </view>
			 <view class="f-s-b b-b c3 pt20 pb20" >
			 	<span>物品总计</span>
				<span class="f28">{{weightTal| fixNum}}</span>
				<span class="f28 cp"></span>
			 </view>
			 <view class="f-s-b b-b c3 pt20 pb20"  >
			 	<span>预估价</span>
				<span class="f28 cr">￥{{amount | fixNum}}</span>
				<span></span>
			 </view>
			 <view class="c3 pt20 pb20"  style=" display: flex;">
			 	<span>物品图片</span>
				
				<span></span>
			 </view>
			 <view class="c3 b-b mt20"  
			  v-for="item,ix in goodList" :key="ix">
			 	<view>{{item.name}}</view>
				<view class="f-s-b  pt20 pb20">
					
					<u--image class="mr20" :src="item.imgUrl" width="120rpx" height='120rpx' mode="widthFix"></u--image>
				    <view class="f-f-c c9 f28">
				    	<span class="ml20 p10">{{item.countType ? '数量':'重量'}}：{{ item.weight| fixNum}}{{item.unit}}</span>
						<span class="ml20 mt20">价格：{{item.price| fixNum }}元/{{item.unit}}</span>
				    </view>
					<view class="">
				     <u-icon @click="redList(item.id,ix)" name="minus-circle-fill" color="#FF4A4A" size="24"></u-icon>
					</view>
				</view>
				<span></span>
			 </view>
		 </view>
		 <view class="fixsure f-s-a">
		 	 <view class="">
		 	 	<view class="">
		 	 		<span class="fb">预估价：</span>
					<span class="cr">￥{{amount| fixNum}}</span>
		 	 	</view>
				<view class="c6 f24 mt20">成交价根据实际重量为准</view>
		 	 </view>
			 <view class="btnsure" @click="addListApi">
			 	确定
			 </view>
		 </view>
		 <u-datetime-picker
			 :show="show"
			 v-model="date"
			  :minDate="Nowdate"
			 mode="datetime"
			 @close='close'
			 @confirm='close'
			 @cancel='close'
		 ></u-datetime-picker>
		 <u-datetime-picker
		 			 :show="show2"
		 			 v-model="date2"
					 :minDate="Nowdate"
		 			 mode="datetime"
		 			 @close='close'
		 			 @confirm='close'
		 			 @cancel='close'
		 ></u-datetime-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				date:1672502400000,
				date2:1672502400000,
				Nowdate:0,
				show:false,
				show2:false,
				userInfo:{
					name:'菜狗一号',
					sex:'男',
					birth:'2000.10.10',
					address:'选择地址',
				},
				goodList:[],
				addressData:{},
				amount:0,
				weightTal:0,
				orderInfo:{},
				isedit:false,
				isend:false,
				MainHeight:0,
				
				
			}
		},
		onReady() {
			this.getScollHeight()
		},
		onShow() {
			// let addresses = uni.getStorageSync('addresses');
			console.log(this.addressData,'addressData')
			let date = new Date().getTime()
			this.Nowdate = date
			this.date = date
			this.date2 = date + 86400000
			// uni.hideBackButton()
		},
		onLoad(option) {
			if(option.data){
				this.isedit = false
				this.goodList = JSON.parse(option.data)
				console.log(this.goodList,'this.goodList111')
				this.amount = 0
				this.weightTal = 0
				this.goodList.map((item)=>{
					item.categorizeName =  item.name
					item.categorizeId =  item.id
					delete  item.id
					delete  item.name
					this.amount += Number(item.weight)*Number(item.price)
					this.weightTal += Number(item.weight)
					return item.amount = Number(item.weight)*Number(item.price)
				})
				// 如果增加订单地址就选默认第一个
				this.getAddressList()
			}else if(option.id){
				this.isedit = true
				this.getDetail(option.id)
				
			}
			
		},
		mounted() {
			
			  var backbutton = document.getElementsByClassName('uni-page-head-btn')[0]
			  if(backbutton) backbutton.style.backgroundColor = 'rgb(0,0,0,0)';
		},
		
		methods: {
			
			getAddressList() {
			  const that = this
			  that.$api.request('get', 'address/app/getAllAddress').then(res => {
			    // that.addressList = res.data
				if(res.data.length>0){
					that.addressData = res.data[0] ? res.data[0] :{}
				}
			  })
			},
			redList(id,ix){
				if(this.isedit){
					this.deleteShow(id,ix)
				}else{
					this.delList(ix)
				}
				
			},
			// 删除后重新计算价格
			delList(ix){
				
				this.goodList.splice(ix,1)
				this.amount = 0
				this.weightTal = 0
				this.goodList.map((item)=>{
					this.amount += Number(item.weight)*Number(item.price)
					this.weightTal += Number(item.weight)
					return item.amount = Number(item.weight)*Number(item.price)
				})
			},
			
			close(){
				this.show = false
				this.show2 = false
			},
			getDetail(id){
				let that = this
				this.$api.request('get', `appOrder/app/${id}`).then(res => {
				 // console.log(res.data,'res')
				 let info = res.data
				 // const  info = JSON.parse(option.info)
				 console.log(info,'info')
						  const {address,city,county,province,latitude,longitude,userId,id,contactor,phone} = info
			     this.addressData = {address,city,county,province,latitude,longitude,userId,id,contactor,phone}
				 
				 // console.log(this.addressData ,'this.addressData')
				 this.weightTal = info.expectWeightTal
				 this.amount =info.expectAmountTal
				 this.date = info.startTime
				 this.date2 = info.endTime
				 this.goodList = info.hsUserWasteVoList
				 
				 console.log(this.goodList,'this.goodList111')
				}).catch(err => {
				  that.$api.msg('请求失败，请稍后再试')
				})
			},
			
			addListApi(){
				this.addOrderList()
			},
			addOrderList(){
				let that = this
				if(that.goodList.length == 0){
					this.$api.msg('未选择回收物品！')
					return
				}
				if(this.addressData == null){
					this.$api.msg('请先选择收货地址')
					return
				}
				if(this.date < this.Nowdate){
					this.$api.msg('开始时间必须大于当前时间')
					return
				}
				if(this.date2 < this.date){
					this.$api.msg('结束时间必须大于开始时间')
					return
				}
				let meth = 'post'
				let url = 'appOrder/app/add'
				if(that.isedit){
					meth = 'put'
					url = 'appOrder/app/edit'
					
				}else{
					delete  this.addressData.id
				}
				console.log(this.goodList,'this.goodList222')
				// return
				this.$api.request(meth, url,Object.assign({
					contactor:this.addressData.consignee,
					// weightTal: this.weightTal,
					expectWeightTal: this.weightTal,
					// amountTal:this.amount,
					expectAmountTal:this.amount,
					startTime: this.formatDate(this.date),
					endTime: this.formatDate(this.date2),
					// appointOrderId:2,
					// riderId: 29,
					hsUserWasteBoList:this.goodList
				},this.addressData)).then(res => {
					that.goodList = []
					that.$api.msg('下单成功')
					setTimeout(()=>{
						that.backPageRefresh()
					},500)
					
				})
			},
			
			 // 返回上一页或者多页
			// 这个函数建议放到公共的地方，很多页面都需要
			backPageRefresh(page) { // page这个值如果你只返回上一页可以不用传，返回上上页就传2，以此类推
				let pages = getCurrentPages(); // 当前页面
				let i = 0
				if (page) {
					i = page - 1
				}
				let beforePage = pages[pages.length - (2 + i)]; // 前一个页面或者更多  beforePage 这个值当你刷新浏览器后是无法返回的，需要用到浏览器历史记录返回上一页 history.back()
				console.log('刷新11')
				if (beforePage && beforePage.$vm.refreshRequest) {
					uni.navigateBack({
						delta: page || 1,
						success: function() {
							console.log('刷新22')
							beforePage.$vm.refreshRequest(); // 执行前一个页面或者前几个页面并且刷新该页面
						}
					});
				} else {
					uni.navigateBack({delta:  1});
					// history.back() // 浏览器的方法返回上一页
				}
			},
			deleteShow(id,ix) {
				if(this.goodList.length == 1){
					this.$api.msg('预约物品最小数量为1条！')
					return
				}
			
			  const that = this
			  uni.showModal({
			    title: '删除提示',
			    content: '您确定要删除该记录吗？',
			    showCancel: true,
			    confirmText: '删除',
			    success: (e) => {
			      if (e.confirm) {
			        that.$api.request('delete', `appOrder/app/delHsWasteById/${id}`,
					).then(res => {
						that.delList(ix)
			        })
			      }
			    },
			    fail: () => {}
			  })
			},
		
			// 设置高度
			getScollHeight(){
				let that = this
				uni.getSystemInfo({
					success: function (res) {
						let windowHeight= res.windowHeight;
						that.MainHeight = (windowHeight - 78 - 189 - 54 +100  ) + 'px';
					}
				});
			},
			formatDate(value,spe='-') {
							// value = value*1000
			   let data= new Date(value);
			   let year = data.getFullYear();
			   let month = data.getMonth() + 1;
			   let day = data.getDate();
			   let h = data.getHours();
			   let mm = data.getMinutes();
			   let s = data.getSeconds();
			   month = month >= 10 ? month : "0" + month;
			   day = day >= 10 ? day : "0" + day;
			   h = h >= 10 ? h : "0" + h;
			   mm = mm >= 10 ? mm : "0" + mm;
			   s = s >= 10 ? s : "0" + s;
			   return `${year}${spe}${month}${spe}${day} ${h}:${mm}:${s}`;
			 },
		}
	}
</script>

<style lang="scss">
	page {
		background: $page-color-base;
		// padding-top: 16upx;
		display: flex;
		flex-direction: column;
		::v-deep  .uni-page-head-btn  {
			background-color: #000 !important;
		}
	}
    .headBg{
		background-image: url('https://chaoyuanhuishou.oss-cn-beijing.aliyuncs.com/homebg.png');
		background-size: 100% 100%;
		// width: 750rpx;
		height: 378rpx;
		// background: #1AC388;
		border-radius: 0rpx 0rpx 40rpx 40rpx;
		opacity: 1;
	}
	.outBtn{
		position: fixed;
		bottom: 200rpx;
		left: 50%;
		transform: translate(-50%,0);
		width: 700rpx;
		height: 88rpx;
		background: #F14647;
		box-shadow: 0rpx 2rpx 4rpx 2rpx rgba(0,0,0,0.16);
		border-radius: 44rpx 44rpx 44rpx 44rpx;
		opacity: 1;
		text-align: center;
		line-height: 88rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #FFFFFF;
	}
	.mainBox{
		margin-top: -200rpx;
		// width: 750rpx;
		// max-height: 792rpx;
		overflow-y: scroll;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 8rpx 2rpx rgba(0,0,0,0.1);
		border-radius: 40rpx 40rpx 8rpx 8rpx;
		opacity: 1;
		padding: 10rpx 32rpx 0;
	}
	.fixsure{
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		height: 156rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -4rpx 8rpx 2rpx rgba(0,0,0,0.1);
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		opacity: 1;
	}
	.btnsure{
		width: 318rpx;
		height: 90rpx;
		background: var(--theme);
		border-radius: 46rpx 46rpx 46rpx 46rpx;
		text-align: center;
		line-height: 90rpx;
		color: #FFFFFF;
	}
	
</style>
